package cn.edu.buu.news.config;

import cn.edu.buu.news.exception.ExceptionInfoEnum;
import cn.edu.buu.news.exception.NewsException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

//此类的实例交由spring容器管理
//鉴权作用
@Component
public class CheckAdminLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    //handler执行之前要进入此拦截方法
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //查看请求头中是否带有token
        String token = request.getHeader("token");
        //如果token为空，说明未登录，请登录
        if (token == null) {
            throw new NewsException(ExceptionInfoEnum.NOTLOGIN.getCode(),ExceptionInfoEnum.NOTLOGIN.getErrorMessage());
        }
        //token不为空，到redis核实是否存在此token对应的登录信息
        Set keys = redisTemplate.keys("news:admin:*:"+token);
        if (keys.size()<1){
            throw new NewsException(ExceptionInfoEnum.NOTLOGIN.getCode(),ExceptionInfoEnum.NOTLOGIN.getErrorMessage());
        }
        //有登录信息，放行,延续下一个30min
        List list =new ArrayList(keys);
        redisTemplate.expire(list.get(0),30, TimeUnit.MINUTES);
        return  true;

    }

}